package com.vmove.childtrain.db;

import android.content.Context;

import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.misc.TransactionManager;
import com.vmove.childtrain.db.entity.Light;
import com.vmove.childtrain.db.entity.Program;

import java.lang.reflect.ParameterizedType;
import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.Callable;

public class BaseDao<T> {

    protected Dao<T, Integer> daoOpe;
    protected DatabaseHelper helper;

    public BaseDao(Context context) {
        try {
            helper = DatabaseHelper.getHelper(context);
            daoOpe = helper.getDao(getTClass());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private Class<T> getTClass()
    {
        Class<T> tClass = (Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        return tClass;
    }

    public List<T> getAll() throws SQLException {
        return daoOpe.queryForAll();
    }

    public T queryById(int id) throws SQLException {
        return daoOpe.queryForId(id);
    }

    public int deleteById(int id) throws SQLException {
        int i = daoOpe.deleteById(id);
        return i;
    }

    public int update(T t) throws SQLException {
        return daoOpe.update(t);
    }

    public int createOrUpdate(T t) throws SQLException {
        return  daoOpe.createOrUpdate(t).getNumLinesChanged();
    }

    public int create(T t) throws SQLException {
        return daoOpe.create(t);
    }

    /**
     * 事务添加多个
     * @return
     */
    public boolean createAll(final List<T> ts) {
        //事务操作
        boolean isSucc=false;
        try {
            isSucc = TransactionManager.callInTransaction(helper.getConnectionSource(),
                    new Callable<Boolean>()
                    {
                        @Override
                        public Boolean call() throws Exception
                        {
                            for (T t:ts) {
                                daoOpe.create(t);
                            }
                            return true;
                        }
                    });
        }catch (SQLException e) {
            isSucc = false;
        }
        return isSucc;
    }
}
